package com.ruoyi.web.task;


import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.city_map.domain.CityMap;
import com.ruoyi.system.city_map.service.ICityMapService;
import com.ruoyi.system.weather_forecast.domain.WeatherForecast;
import com.ruoyi.system.weather_forecast.domain.WeatherForecastWapper;
import com.ruoyi.system.weather_forecast.service.IWeatherForecastService;
import com.ruoyi.web.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 天气预报
 *
 * @author xuezhenwei
 * @date 2024-06-21 15:25
 */
@Component("weatherForecastTask")
public class WeatherForecastTask {

    @Autowired
    private HttpUtils httpUtils;

    @Autowired
    private ICityMapService iCityMapService;

    @Autowired
    private IWeatherForecastService iWeatherForecastService;

    private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    // 获取15日天气预报
    public void task() {

        List<CityMap> cityMaps = iCityMapService.selectCityMapList(new CityMap());

        if (CollectionUtils.isEmpty(cityMaps))
            return;

        Iterator<CityMap> iterator = cityMaps.iterator();

        String url = "https://api.seniverse.com/v3/weather/daily.json";
        Map map = new HashMap();
        map.put("lang", "zh-Hans");
        map.put("key", "SfOcYG07nsrQQ2w8G");
        map.put("unit", "c");
        map.put("start", 0);
        map.put("days", 15);

        while (iterator.hasNext()) {
            CityMap cityMap = iterator.next();
            map.put("location", cityMap.getCityId());
            String result = httpUtils.httpUtil(map, url);
            WeatherForecastWapper weatherForecastWapper = WeatherForecastWapper.objectFromData(result);

            Iterator<WeatherForecastWapper.Result> iterator1 = weatherForecastWapper.getResults().iterator();

            while (iterator1.hasNext()) {
                WeatherForecastWapper.Result obj = iterator1.next();
                List<WeatherForecast> weatherForecasts = obj.getDaily();
                if (!CollectionUtils.isEmpty(weatherForecasts)) {
                    String dateText = simpleDateFormat.format(new Date()) + cityMap.getCityId();
                    iWeatherForecastService.deleteWeatherForecastByDateText(dateText);
                    for (WeatherForecast weatherForecast : weatherForecasts) {
                        weatherForecast.setDateText(simpleDateFormat.format(new Date()) + cityMap.getCityId());
                        weatherForecast.setId(IdUtil.getSnowflakeNextIdStr());
                        weatherForecast.setCreatedAt(new Date());
                        weatherForecast.setUpdatedAt(new Date());
                    }
                    iWeatherForecastService.creates(weatherForecasts);
                }
            }
        }

    }

    /**
     * 通过接口获取远程雷达图片
     */
    public void radarTask() {
        //真实地址http://sdsqxt.cn:15010/products/Radar/Sradar/2024/11/01/2411010903_000.png
        String baseUrl = "http://sdsqxt.cn:15010/products/Radar/Sradar/";
        String endUrl = "_000.png";
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(6);
        String year = String.valueOf(localDateTime.getYear());
        String month = localDateTime.getMonthValue() < 10 ? "0" + localDateTime.getMonthValue() : String.valueOf(localDateTime.getMonthValue());
        String day = localDateTime.getDayOfMonth() < 10 ? "0" + localDateTime.getDayOfMonth() : String.valueOf(localDateTime.getDayOfMonth());
        String hour = localDateTime.getHour() < 10 ? "0" + localDateTime.getHour() : String.valueOf(localDateTime.getHour());
        String minute = localDateTime.getMinute() < 10 ? "0" + localDateTime.getMinute() : String.valueOf(localDateTime.getMinute());
        String fileName = year.substring(2) + month + day + hour + minute + endUrl;
        String imageUrl = baseUrl + year + "/" + month + "/" + day + "/" + fileName;
        String savePath = RuoYiConfig.getProfile() + "/leida/" + fileName;

        try {
            URL url = new URL(imageUrl);
            InputStream inputStream = url.openStream();
            FileOutputStream outputStream = new FileOutputStream(savePath);
            byte[] buffer = new byte[4096];
            int byteRead;
            while ((byteRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, byteRead);
            }
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
